package cn.huihuo.weibo.service;

import cn.huihuo.weibo.bean.ResponsePicBean;
import cn.huihuo.weibo.module.ProductPic;
import com.google.gson.Gson;
import com.jfinal.kit.PropKit;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author Dan
 * Created by zhengjunbo on 2015/10/19.
 */
public class DownLoadProductPic {
    public static final  DownLoadProductPic service =new DownLoadProductPic();
    private BlockingQueue<ProductPic> queue = new ArrayBlockingQueue<>(1000);

    public DownLoadProductPic(){
        new Thread(() -> takeAndUpdate()).start();

    }

    public boolean addPic(ProductPic pic){
        return queue.offer(pic);
    }


    public void takeAndUpdate(){
        while (true){
            ProductPic productPic ;
            try {
                 productPic = queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
                continue;
            }
            int i=0;
            while (true) {

                String picJson = null;
                try {
                    picJson = getPicJson(productPic.get("out_pic_path"));
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                System.out.println("收到的图片:"+picJson);

                Gson gson = new Gson();
                ResponsePicBean responsePicBean = gson.fromJson(picJson, ResponsePicBean.class);

                if (responsePicBean.getStatus().equals("1")) {
                    productPic.set("inner_pic_path", responsePicBean.getUrl()).update();
                    break;
                }
                if(i==2){
                    break;
                }
                i++;
            }
        }
    }


    public String getPicJson(String url)  {

        String str ;
        try {
            HttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
            HttpGet get  = new HttpGet(PropKit.use("config.properties").get("picRequest")+"?sourceUrl="+url);

            HttpResponse execute = httpClient.execute(get);




            str = EntityUtils.toString(execute.getEntity(), "utf-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return str;
    }

}
